package com.dlyk.aspect;

import com.dlyk.commons.DataScope;
import com.dlyk.constant.Constants;
import com.dlyk.query.BaseQuery;
import com.dlyk.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.annotation.Annotation;
import java.util.List;

/**
 * @description:
 * @author: ajie
 * @date: 2024/7/17 22:44:08
 * @version: 1.0
 */
@Aspect
@Component
public class DataScopeAspect {

    //aspectJ 实现aop

    //切入点
    @Pointcut(value = "@annotation(com.dlyk.commons.DataScope)")
    private void  pointCut(){

    }

    @Around(value = "pointCut()")//环绕增强
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        //拿到方法上的注解
        DataScope dataScope = methodSignature.getMethod().getDeclaredAnnotation(DataScope.class);

        String tableAlias = dataScope.tableAlias();
        String tableField = dataScope.tableField();

        //在spring web容器中，可以拿到当前请求的request对象
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader(Constants.TOKEN_NAME);
        //从token中解析出该用户是管理员还是普通用户
        List<String> roleList = JWTUtils.parseJWTByUserRole(token);
        Integer userId = JWTUtils.parseJWTByUserId(token);

        if (!roleList.contains("admin")) {//不包含admin，只查当前用户自己的数据，否则查所有数据
            Object params = joinPoint.getArgs()[0];//拿到方法的第一个参数
            if (params instanceof BaseQuery){
                BaseQuery query = (BaseQuery) params;

                //select * from t_activity ta where ta.owner_id = 2 (普通用户：于嫣)
                query.setFilterSQL(" and " + tableAlias + "." + tableField + "=" + userId);
            }
        }
        System.out.println("目标方法执行之前=========");
        Object reslut = joinPoint.proceed();
        System.out.println("目标方法执行之后=========");
        return reslut;
    }

}
